<?php

/**
 * 印尼短信接口：支持下发短信（支持群发），可用于 找回密码，短信告警，发送活动通知等
    Endpoint for SMS Longnumber:  
    http://203.166.197.162/ApiLongNumber/receive.php
    Longnumber credentials :
    uid:*****
    pwd:*****
    sc:LONGNUMBER
 */
class SMS_OTP extends SMS_Abstract {

    /**
     * 帐号
     *
     * */
    private $_account = '';

    /**
     * 密钥
     *
     * */
    private $_seckey = '';
    
    /**
     * 发放方名称
     * @var type 
     */
    private $_senderName = '';

    /**
     * 构造函数
     * @param <type> $option
     */
    public function __construct($option = array()) {

        if (isset($option['account'])) {
            $this->setAccount($option['account'], $option['seckey']);
        }
        if (isset($option['sender_name'])) {
            $this->_senderName = $option['sender_name'];
        }

        parent::__construct($option);
    }

    /**
     * 设置帐号
     * @param <type> $account
     * @param <type> $seckey
     * */
    public function setAccount($account, $seckey) {

        $this->_account = $account;
        $this->_seckey = $seckey;
    }

    /**
     * 发送短信
     * @param <type> $mobile 接收手机号，必须以 62 开头
     * @param <type> $content （必须 utf8 格式）
     *
     * @return 发送成功条数
     */
    public function send($mobile, $content) {

        $transid = time().mt_rand(1000, 9999);
        $param = array(
            'uid' => $this->_account,
            'pwd' => $this->_seckey,
            'serviceid' => 1000,
            'msisdn' => '62'.ltrim($mobile, '0'),
            'sms' => $content,
            'transid' => $transid, // 业务唯一id
            'smstype' => 0,
            'sc' => 'LONGNUMBER',
        );
        $url = 'http://203.166.197.162/ApiLongNumber/receive.php?'. http_build_query($param);

        $res = $this->_send($url);
        
//        echo $url, PHP_EOL;
//        echo $res, PHP_EOL;
        
        $match = array();
        preg_match('/\<status\>(.*?)\<\/status\>/i', $res, $match);
        $status = intval($match[1]);
        if ($status > 0) {
            $msg = 'unknown error';
            if (preg_match('/\<msg\>(.*?)\<\/msg\>/i', $res, $match)) {
                $msg = trim($match[1]);
            }
            throw new SMS_Exception($msg, SMS_Exception::E_SMS_SEND_ERROR);
        }

        return true;
    }

    /**
     * 发送请求
     *
     * @param <type> $url
     * */
    public function _send($url) {

        return file_get_contents($url);
    }

}
